package com.junyuan.fxf_pad.application;

import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Toast;

import com.baidu.apistore.sdk.ApiStoreSDK;
import com.junkchen.blelib.BleService;
import com.junyuan.fxf_pad.utils.BytesUtil;

import java.util.List;

/**
 * Created by Administrator on 2016/8/30.
 */
public class MyApplication extends Application {

    public static MyApplication instance;
    public BleService mBleService;
    public BluetoothGattCharacteristic mCharacteristic;
    String backData;


    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        ApiStoreSDK.init(this, "8979790e60699e9682cf8bb238af045a");


        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_GATT_CONNECTED);
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        registerReceiver(bleReceiver, filter);
    }

    public BroadcastReceiver bleReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BleService.ACTION_GATT_CONNECTED)) {
                Toast.makeText(getApplicationContext(), "蓝牙以连接", Toast.LENGTH_SHORT).show();
                sendAndReceiveData();
                Log.d("mytag", "蓝牙链接");
            } else if (intent.getAction().equals(BleService.ACTION_GATT_DISCONNECTED)) {
                Toast.makeText(getApplicationContext(), "蓝牙以断开", Toast.LENGTH_SHORT).show();
                Log.d("mytag", "蓝牙断开");
                mBleService.initialize();
                mBleService.enableBluetooth(true);
                mBleService.scanLeDevice(true, 50000);
                mBleService.setOnLeScanListener(new BleService.OnLeScanListener() {
                    @Override
                    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                        if (device.getName() != null) {
                            if (device.getName().equals("HMSoft") || device.getName().equals("CC66") || device.getName().equals("CC41")) {
                                BluetoothDevice mDevice = device;
                                Log.d("mytag", "获得到的mDevice:" + mDevice);
                                mBleService.connect(mDevice.getAddress());
                            }
                        }
                    }
                });
            }
        }
    };


    public void sendAndReceiveData() {


        mBleService.setOnServicesDiscoveredListener(new BleService.OnServicesDiscoveredListener() {
            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                Log.d("mytag", "onServicesDiscovered Status:" + status);

                List<BluetoothGattService> Services = gatt.getServices();
                for (BluetoothGattService service : Services) {
                    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                    for (BluetoothGattCharacteristic characteristic : characteristics) {
                        if (characteristic.getUuid().toString().equals("0000ffe1-0000-1000-8000-00805f9b34fb")) {
                            mBleService.setCharacteristicNotification(characteristic, true);
                            mCharacteristic = characteristic;
//                            boolean isSend = mBleService.writeCharacteristic(characteristic, "hello");
//                            Log.d("mytag", "是否发送成功" + isSend);
                        }
                    }
                }
            }
        });


        mBleService.setOnDataAvailableListener(new BleService.OnDataAvailableListener() {

            @Override
            public void onCharacteristicRead(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, int status) {
                //处理特性读取返回的数据(暂时不用)
                Log.d("mytag", "onCharacteristicRead Status:" + status);
                List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
                for (BluetoothGattDescriptor descriptor : descriptors) {
                    String data = BytesUtil.bytesToHexString(descriptor.getValue());
//                    backData=data;
                    Log.d("mytag", "onCharatersiticRead Data:" + data);
                }

            }


            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                //处理通知返回的数据(当收到数据改变通知时调用)
                Log.d("mytag", "onCharacteristicChanged");
                Log.d("mytag", "收到蓝牙发来数据：" + new String(characteristic.getValue()));
                backData = new String(characteristic.getValue());

                Intent intent = new Intent();
                intent.setAction("BackData");
                intent.putExtra("BackData", backData);
                sendBroadcast(intent);
            }

            @Override
            public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
                Log.d("mytag", "onDescriptorRead");
            }
        });

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        mBleService.disconnect();
        unregisterReceiver(bleReceiver);
    }
}
